using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

[CSharpCallLua]
public class ViewMode : MonoBehaviour
{
    public static LuaEnv luaEnv = new LuaEnv();//全局Lua环境
    protected LuaTable scriptEnv;
    public LuaTable luaViewMode=>scriptEnv;
    public TextAsset luaScript;
    private Action LuaStart; //生命周期方法
    private Action LuaOnEnable; //生命周期方法
    private Action LuaUpdate; //生命周期方法
    private Action LuaOnDisable; //生命周期方法
    private Action LuaOnDestroy; //生命周期方法
    private Action<Collider> LuaOnTriggerEnter;
    private Action<Collider> LuaOnTriggerExit;

    [CSharpCallLua]
    private static Func<LuaTable> NewViewMode;

    protected virtual void Awake()
    {
        ////////////////////////这段代码提到全局的LuaManager中去////////////////////////////
         luaEnv.DoString("mvvm= require 'Mvvm'");
        NewViewMode = luaEnv.Global.GetInPath<Func<LuaTable>>("mvvm.NewViewMode");
        ////////////////////////这段代码提到全局的LuaManager中去END////////////////////////////
        scriptEnv = /*LuaManager.*/NewViewMode();
        var meta = luaEnv.NewTable();//原表
        meta.Set("__index", luaEnv.Global);
        scriptEnv.SetMetaTable(meta);//设置原表
        meta.Dispose();//销毁原表

        scriptEnv.Set("this", this);
        scriptEnv.Set("self", scriptEnv);

        //执行Lua脚本
        luaEnv.DoString(luaScript.text, luaScript.name, scriptEnv);
      
        Action awake = scriptEnv.Get<Action>("Awake");
        GetLuaFunction();
        awake?.Invoke();
    }

    protected virtual void GetLuaFunction()
    {
        //导出生命周期方法
        LuaStart = scriptEnv.Get<Action>("Start");
        LuaOnEnable = scriptEnv.Get<Action>("OnEnable");
        LuaOnDisable = scriptEnv.Get<Action>("OnDisable");
        LuaOnDestroy = scriptEnv.Get<Action>("OnDestroy");
        LuaOnTriggerEnter = scriptEnv.Get<Action<Collider>>("OnTriggerEnter");
        LuaOnTriggerExit = scriptEnv.Get<Action<Collider>>("OnTriggerExit");
    }

    private void Start() => LuaStart?.Invoke();

    private void OnEnable() => LuaOnEnable?.Invoke();

    private void OnDisable() => LuaOnEnable?.Invoke();

    private void OnDestroy() => LuaOnDestroy?.Invoke();

    private void OnTriggerEnter(Collider other) => LuaOnTriggerEnter?.Invoke(other);

    private void OnTriggerExit(Collider other) => LuaOnTriggerExit?.Invoke(other);
}